<template>
    <el-form @submit.prevent :model="model" v-bind="_options" ref="formRef" :inline="model.inlineFlag" :labelWidth="model.labelWidth" :size="model.size?model.size:'default'">
        <template v-for="(item, index) in fieldList" :key="index">
            <!-- 隐藏、显示 -->
            <div v-if="item.showFlag === 'hide'">
            </div>
             <!-- 单选框 -->
            <el-form-item :label="item.label" v-else-if="item.type === 'radio'" :rules="item.rules" :prop="[item.field]">
                <el-radio-group v-model="model[item.field]" :disabled="item.disabled">
                    <el-radio
                        :label="val[item.options?.valueKey || 'value']"
                        size="large"
                        v-for="val in item.options?.data"
                        :key="val[item.options?.valueKey || 'value']">
                        {{ val[item.options?.labelkey || 'label'] }}
                    </el-radio>
                </el-radio-group>
                <el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
            </el-form-item>
            <!-- 复选框 -->
            <el-form-item
                :label="item.label"
                v-else-if="item.type === 'checkbox'"
                :rules="item.rules"
                :prop="[item.field]">
                <el-checkbox-group v-model="model[item.field]" :disabled="item.disabled">
                    <el-checkbox
                        v-for="c in item.options?.data"
                        :key="c[item.options?.valueKey || 'value']"
                        :label="c[item.options?.valueKey || 'value']"
                        >{{ c[item.options?.labelkey || 'label'] }}</el-checkbox
                    >
                </el-checkbox-group><el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
            </el-form-item>
            <!-- 下拉框 -->
            <el-form-item
                :label="item.label"
                v-else-if="item.type === 'select'"
                :rules="item.rules"
                :prop="[item.field]">
                <el-select v-model="model[item.field]" :multiple="item.multiple" :placeholder="item.options ? item.placeholder : '请选择'" :clearable="item.clearable">
                    <el-option
                        v-for="s in item.options?.data"
                        :key="s[item.options?.valueKey || 'value']"
                        :label="s[item.options?.labelkey || 'label']"
                        :value="s[item.options?.valueKey || 'value']" />
                </el-select><el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
            </el-form-item>
            <!-- 选择日 -->
            <el-form-item
                :label="item.label"
                v-else-if="item.type === 'date'"
                :rules="item.rules"
                :prop="[item.field]">
                <el-date-picker
                    v-model="model[item.field]"
                    :readonly="item.readonly"
                    :type="item.type"
                    :placeholder="item.placeholder || item.label"
                    :clearable="item.clearable"
                />
                <el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
            </el-form-item>
            <!-- 选择月 -->
            <el-form-item
                :label="item.label"
                v-else-if="item.type === 'month'"
                :rules="item.rules"
                :prop="[item.field]">
                <el-date-picker
                    v-model="model[item.field]"
                    :readonly="item.readonly"
                    :type="item.type"
                    :placeholder="item.placeholder || item.label"
                    :clearable="item.clearable"
                />
                <el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
            </el-form-item>
            <!-- WangEditor编辑器 -->
            <el-form-item
                :label="item.label"
                v-else-if="item.type === 'WangEditor'"
                :rules="item.rules"
                :prop="[item.field]">
                <WangEditor v-model="model[item.field]" />
                <el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
            </el-form-item>
            <!-- 复制链接输入框 -->
            <el-form-item :label="item.label" :rules="item.rules" :prop="[item.field]" v-else-if="item.type === 'copy'">
                <el-input
                    v-model="model[item.field]"
                    :maxlength="item.maxlength"
                    :readonly="item.readonly"
                    :type="text"
                    :placeholder="item.placeholder || item.label"
                    :disabled="item.disabled" 
                    :showPassword="item.showPassword"
                    :clearable="item.clearable">
                    
                    <template #append>
                        <el-button type="primary" link @click="copyClick(model[item.field])">复制链接</el-button>
                    </template>
                </el-input>

                <el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
            </el-form-item>
            <!-- 图片上传 -->
            <el-form-item :label="item.label" :rules="item.rules" :prop="[item.field]" v-else-if="item.type === 'upload'">
                <Uploadimg
                    :imgUrl="model[item.field]" 
                    @getUrl="getIdCardFrontUrl"
                    @changeUrl="changeUrl(item)"
                    :limit="1"
                    accept=".png,.jpg"
                    >
                </Uploadimg>
                <!-- <el-upload
                    class="avatar-uploader"
                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :on-change="handleChange"
                    :auto-upload="false"
                >
                    <img v-if="model[item.field]" :src="model[item.field]" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload> -->

            </el-form-item>
            <!-- 右侧有单位提示输入框 -->
             <!-- 数字输入框 -->
            <el-form-item :label="item.label" :rules="item.rules" :prop="[item.field]" v-else-if="item.type === 'number'">
                <el-input-number
                    v-model="model[item.field]"
                    :max="item.max"
                    :min="item.min"
                    :readonly="item.readonly"
                    :type="item.type ?? 'text'">
                    <template #append v-if="item.append">{{ item.append }}</template>
                </el-input-number>
                <el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
                
            </el-form-item>
            <!-- 默认输入框 -->
            <el-form-item :label="item.label" :rules="item.rules" :prop="[item.field]" v-else>
                <el-input
                    v-model="model[item.field]"
                    :maxlength="item.maxlength"
                    :readonly="item.readonly"
                    :type="item.type ?? 'text'"
                    :placeholder="item.placeholder || item.label"
                    :disabled="item.disabled" 
                    :showPassword="item.showPassword"
                    :clearable="item.clearable"
                    :showWordLimit="item.maxlength?true:false"
                    @keyup.enter="handleKeyUp(item.enterable)">
                    <template #append v-if="item.append">{{ item.append }}</template>
                </el-input>
                <el-popover
                    placement="top-start"
                    v-if="item.tooltip" 
                    :title="item.popoverTitle"
                    width="200"
                    trigger="hover"
                    :content="item.tooltip"
                >
                    <template #reference>
                        <el-icon  color="#409EFC" size="18"><QuestionFilled /></el-icon>
                    </template>
                </el-popover>
                
            </el-form-item>
            
        </template>

        <el-form-item>
            <slot name="buttons" :model="model" :formRef="formRef">
                <el-button v-if="_options.showSubmitButton" type="primary" @click="onSubmit(formRef)" >
                    <el-icon ><Search /></el-icon> &nbsp;
                    {{ _options.submitButtonText }}
                </el-button>
                <el-button v-if="_options.showResetButton"  @click="resetForm(formRef)">
                    <el-icon><Refresh /></el-icon>  &nbsp;
                    {{ _options.resetButtonText }}
                </el-button>
                <el-button v-if="_options.showCancelButton" @click="emit('cancel')">
                    
                    {{ _options.cancelButtonText }}
                </el-button>
                
                <el-button type="primary"  v-if="_options.showDownloadButton" @click="download(formRef)">
                    <el-icon><Download /></el-icon> &nbsp;
                    {{ _options.downloadButtonText }}
                </el-button>
            </slot>
        </el-form-item>
    </el-form>
</template>
<script lang="ts" setup>
    import type { FormInstance } from 'element-plus'
    import Uploadimg from '@/components/upload/index.vue'
    import WangEditor from '@/components/WangEditor/index.vue'
    import { ComputedRef, ref, computed } from 'vue'
    // 父组件传递的值
    interface Props {
        fieldList: Form.FieldItem[]
        model?: Record<string, any>
        options?: Form.Options
    }
    // 表单的数据
    const model = ref<Record<string, any>>({})
    const formRef = ref<FormInstance>()
    const props = defineProps<Props>()
    // 设置option默认值，如果传入自定义的配置则合并option配置项
    const _options: ComputedRef<Form.Options> = computed(() => {
        const option = {
            labelPosition: 'right',
            disabled: false,
            submitButtonText: '提交',
            resetButtonText: '重置',
            cancelButtonText: '取消'
        }
        return Object.assign(option, props?.options)
    })
    interface EmitEvent {
        (e: 'submit', params: any): void
        (e: 'reset'): void
        (e: 'cancel'): void
    }
    const emit = defineEmits<EmitEvent>()
    defineExpose({
        formRef
    })
    // const model = ref<Record<string, any>>({})
    // 根据fieldList初始化model， 如果model有传值就用传递的model数据模型，否则就给上面声明的model设置相应的(key,value) [item.field]， item.value是表单的默认值（选填）
    props.fieldList.map((item: Form.FieldItem) => {
        // 如果类型为checkbox，默认值需要设置一个空数组
        const value = item.type === 'checkbox' ? [] : ''
        props.model ? (model.value = props.model) : (model.value[item.field] = item.value || value)
    })
    // 提交按钮
    const onSubmit = (formEl: FormInstance | undefined) => {
        console.log(model.value)
        if (!formEl) return
        formEl.validate((valid) => {
            if (valid) {
                emit('submit', model.value)
            } else {
                return false
            }
        })
    }
    // 输入框回车事件
	const handleKeyUp = (enterable: boolean | undefined) => {
	    if (!enterable) return
	    onSubmit(formRef.value)
	}
	// 重置
    const resetForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
    }
    // 复制链接
    const copyClick = (value:string) => {
        window.$copy.copyDomText(value)
    }
    // 下载
    const download = (formEl: FormInstance | undefined) => {
        console.log('download')
    }
    // 上传
    const urls = ref('');
    const getIdCardFrontUrl = (url:any) => {
        urls.value = url;
    };
    const changeUrl = (item:any) => {
        model.value[item.field] = urls.value;
    }

    const handleChange = (res: any,file: any,item:any) => {
        console.log(res)
        console.log(file)
        console.log(item)
    }
</script>
<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
